package com.miyuan.view.home;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.github.lzyzsd.circleprogress.DonutProgress;
import com.miyuan.R;
import com.miyuan.base.BaseFragment;
import com.miyuan.bean.ResultBean;
import com.miyuan.bean.request.MachineListParam;
import com.miyuan.bean.respone.GoodsListBean;
import com.miyuan.bean.respone.MachineListBean;
import com.miyuan.net.NetService;
import com.miyuan.net.RetrofitClient;
import com.miyuan.utils.SPUtils;
import com.miyuan.view.machine.MachineGoodsListActivity;

import com.miyuan.view.widget.LoadingDialog;
import com.miyuan.view.widget.ProgressWheel;

import net.idik.lib.slimadapter.SlimAdapter;
import net.idik.lib.slimadapter.SlimInjector;
import net.idik.lib.slimadapter.ex.loadmore.SimpleLoadMoreViewCreator;
import net.idik.lib.slimadapter.ex.loadmore.SlimMoreLoader;
import net.idik.lib.slimadapter.viewinjector.IViewInjector;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 售货机
 */

public class MachineListFragment extends BaseFragment {
    @BindView(R.id.machine_list)
    RecyclerView machineList;
    @BindView(R.id.search_page_edit)
    EditText searchPageEdit;
    @BindView(R.id.swipeRefresh)
    SwipeRefreshLayout swipeRefreshLayout;

    private SlimAdapter slimAdapter;

    private boolean hasMore = true;
    private int current = 1;
    private String parameter = "";
    private int size = 200;

    public static MachineListFragment newInstance() {
        MachineListFragment machineListFragment = new MachineListFragment();
        machineListFragment.setArguments(new Bundle());
        return machineListFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setFragmentLayout(R.layout.fragment_machine_list);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        loadingDialog.show();
        initList(new ArrayList());
        getMachineList();
        searchPageEdit.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    parameter = searchPageEdit.getText().toString().trim();
                    current = 1;
                    loadingDialog.show();
                    getMachineList();
                }
                return false;
            }
        });
    }

    public void getMachineList() {
        RetrofitClient.getInstance()
                .create(NetService.class)
                .getMachineList(new MachineListParam(current, parameter, size).toRequestBody())
                .enqueue(new Callback<ResultBean<MachineListBean>>() {

                    @Override
                    public void onResponse(Call<ResultBean<MachineListBean>> call, Response<ResultBean<MachineListBean>> response) {
                        loadingDialog.dismiss();
                        if (swipeRefreshLayout != null) {
                            swipeRefreshLayout.setRefreshing(false);
                        }
                        ResultBean<MachineListBean> resultBean = response.body();
                        if (resultBean != null) {
                            if (resultBean.getData() != null) {
                                slimAdapter.updateData(resultBean.getData().getRecords());
                                int listSize = resultBean.getData().getRecords().size();
                                hasMore = listSize >= size;
//                            } else if (resultBean.getCode() == 300006) {
//                                Toast.makeText(getActivity(), "请重新登录", Toast.LENGTH_SHORT).show();
//                                SPUtils.getInstance().remove("Authorization", true);
//                                Intent i = getActivity().getPackageManager().getLaunchIntentForPackage(getActivity().getPackageName());
//                                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                                startActivity(i);
//                                getActivity().finish();
                            } else {
                                Toast.makeText(getActivity(), resultBean.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ResultBean<MachineListBean>> call, Throwable t) {
                        loadingDialog.dismiss();
                        if (swipeRefreshLayout != null) {
                            swipeRefreshLayout.setRefreshing(false);
                        }
                    }
                });
    }

    @OnClick(R.id.search_text)
    public void onSearch() {
        parameter = searchPageEdit.getText().toString().trim();
        current = 1;
        loadingDialog.show();
        getMachineList();
    }

    public void initList(List list) {
        if (machineList != null) {
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
            linearLayoutManager.setOrientation(OrientationHelper.VERTICAL);
            machineList.setLayoutManager(linearLayoutManager);
            slimAdapter = SlimAdapter.create().register(R.layout.item_machine_list, new SlimInjector<MachineListBean.RecordsBean>() {
                @Override
                public void onInject(final MachineListBean.RecordsBean data, IViewInjector injector) {
                    injector.text(R.id.machine_location, data.getPointName());
                    injector.findViewById(R.id.item_root).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(getActivity(), MachineGoodsListActivity.class);
                            intent.putExtra("vendorId", data.getId());
                            intent.putExtra("controlNumber", data.getControlNumber());
                            startActivity(intent);
                        }
                    });
                    if (data.getLastReplenishmentTime() != null) {
                        injector.text(R.id.last_time, "上次补货时间：" + data.getLastReplenishmentTime());
                    } else {
                        injector.text(R.id.last_time, "上次补货时间：");
                    }
                    injector.text(R.id.machine_code, data.getNumber());
                    if (data.getPicture() != null) {
                        ImageView machineImg = (ImageView) injector.findViewById(R.id.machine_img);
                        Glide.with(getActivity())
                                .load(data.getPicture())
                                .into(machineImg);
                    } else {
                        injector.image(R.id.machine_img, R.mipmap.machine_default);
                    }
                    DonutProgress donutProgress = (DonutProgress) injector.findViewById(R.id.progress_wheel);
                    int percent = (int) Float.parseFloat(data.getSalesRatioString());
                    if (percent >= 100) {
                        donutProgress.setText("已售");
                        donutProgress.setDonut_progress("100");
                        donutProgress.setFinishedStrokeColor(Color.TRANSPARENT);
                        donutProgress.setUnfinishedStrokeColor(Color.TRANSPARENT);
                    } else {
                        donutProgress.setText((100 - percent) + "%");
                        donutProgress.setDonut_progress((100 - percent) + "");
                        donutProgress.setFinishedStrokeColor(Color.parseColor("#4DABF5"));
                        donutProgress.setUnfinishedStrokeColor(Color.parseColor("#DDEFFE"));
                    }
                }
            }).enableLoadMore(new SlimMoreLoader(getActivity(), new SimpleLoadMoreViewCreator(getActivity()).setNoMoreHint("").setLoadingHint("").setPullToLoadMoreHint("")) {
                @Override
                protected void onLoadMore(final Handler handler) {
                    ++current;
                    RetrofitClient.getInstance()
                            .create(NetService.class)
                            .getMachineList(new MachineListParam(current, parameter, size).toRequestBody())
                            .enqueue(new Callback<ResultBean<MachineListBean>>() {

                                @Override
                                public void onResponse(Call<ResultBean<MachineListBean>> call, Response<ResultBean<MachineListBean>> response) {
                                    loadingDialog.dismiss();
                                    if (swipeRefreshLayout != null) {
                                        swipeRefreshLayout.setRefreshing(false);
                                    }
                                    ResultBean<MachineListBean> resultBean = response.body();
                                    if (resultBean.getData() != null) {
                                        handler.loadCompleted(resultBean.getData().getRecords());
                                        int listSize = resultBean.getData().getRecords().size();
                                        hasMore = listSize >= size;
                                    } else {
                                        Toast.makeText(getActivity(), resultBean.getMsg(), Toast.LENGTH_SHORT).show();
                                    }
                                }

                                @Override
                                public void onFailure(Call<ResultBean<MachineListBean>> call, Throwable t) {
                                    loadingDialog.dismiss();
                                    if (swipeRefreshLayout != null) {
                                        swipeRefreshLayout.setRefreshing(false);
                                    }
                                }
                            });
                }

                @Override
                protected boolean hasMore() {
                    return hasMore;
                }
            }).attachTo(machineList);
            swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
            swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    current = 1;
                    getMachineList();
                }
            });
            slimAdapter.updateData(list);
        }
    }
}
